package com.ie.sevice.before;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ie.common.http.ResponseResult;
import com.ie.entity.CartEntity;
import com.ie.mapper.before.CartMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;import java.util.Map;

/**
 * @classname: CartServiceImpl
 * @Author: S2
 * @Description: //TODO
 * @Date: 2025/5/29  10:30
 * @Param:
 * @version: 1.0
 **/
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, CartEntity> implements CartService {
    @Override
    public ResponseResult<Map<String, Object>> addCart(CartEntity cartEntity) {
        Long goodsnum = lambdaQuery()
                .eq(CartEntity::getBusertableId, cartEntity.getBusertableId())
                .eq(CartEntity::getGoodstableId, cartEntity.getGoodstableId())
                .count();
        boolean s = false;
        if (goodsnum > 0) {
            LambdaUpdateWrapper<CartEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(CartEntity::getShoppingnum, cartEntity.getShoppingnum() + 1)
                    .eq(CartEntity::getBusertableId, cartEntity.getBusertableId())
                    .eq(CartEntity::getGoodstableId, cartEntity.getGoodstableId());
            s = update(lambdaUpdateWrapper);
        } else {// 添加新的商品到购物车
            s = save(cartEntity);
        }
        if (s) {
            return ResponseResult.getMessageResult(null, "A001");
        } else {
            return ResponseResult.getMessageResult(null, "A002");
        }
    }

    @Override
    @Transactional
    public ResponseResult<Map<String, Object>> bupDateCart(CartEntity cartEntity) {
        // CartEntity(id=null, busertableId=null, goodstableId=null, shoppingnum=null, bshoppingnum=[2, 2, 1], bcid=[32, 33, 34])
        //购物车的id列表
        List<Integer> bcid = cartEntity.getBcid();
        //购物车的数量列表
        List<Integer> bshoppingnum = cartEntity.getBshoppingnum();

        ArrayList<CartEntity> cartEntities = new ArrayList<CartEntity>();
        for (int i = 0; i < bcid.size(); i++) {
            CartEntity cart = new CartEntity();
            cart.setId(bcid.get(i));
            cart.setShoppingnum(bshoppingnum.get(i));
            cartEntities.add(cart);
        }
        boolean b = updateBatchById(cartEntities);
        if (b) {
            return ResponseResult.getMessageResult(null, "A001");
        } else {
            return ResponseResult.getMessageResult(null, "A002");
        }
    }

    //清空购物车

}